﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace VCDepend.Engine
{
  public class TrimmingTextReader : TextReader
  {
    private TextReader m_reader;

    public TrimmingTextReader(TextReader textReader)
    {
      m_reader = textReader;
    }

    public override string ReadToEnd()
    {
      return Trim(m_reader.ReadToEnd());
    }

    public override string ReadLine()
    {      
      return Trim(m_reader.ReadLine());
    }

    public override int Read()
    {
      return m_reader.Read();
    }

    public override int Read(char[] buffer, int index, int count)
    {
      return m_reader.Read(buffer, index, count);
    }

    public override int ReadBlock(char[] buffer, int index, int count)
    {
      return m_reader.ReadBlock(buffer, index, count);
    }

    public string ReadUntil(Regex terminator)
    {
      StringBuilder result = new StringBuilder();

      string line = ReadLine();
      while (line != null && !terminator.IsMatch(line))
      {
        result.AppendLine(line);
        line = ReadLine();
      }

      return result.ToString();
    }

    public void SkipUntil(Regex terminator)
    {
      string line = null;

      do
      {
        line = ReadLine();
      }
      while (line != null && !terminator.IsMatch(line));
    }

    public override int Peek()
    {
      return m_reader.Peek();
    }

    protected override void Dispose(bool disposing)
    {
      if (disposing)
        m_reader.Dispose();
    }

    public override void Close()
    {
      m_reader.Close();
    }

    private string Trim(string value)
    {
      if (value == null)
        return null;

      return value.Trim();
    }
  }
}
